package api;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

public class AbsApiServlet extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         req.setCharacterEncoding("utf-8");
         resp.setCharacterEncoding("utf-8");
         resp.setContentType("application/json");
        Object result ;
        try {
           result = new Object() {
                 public final boolean success = true;
                 public final Object data = doGetInner(req, resp);
             };
         }catch(Exception exc){
              result = new Object(){
               public final boolean success = false;
              public final String reason = exc.getMessage();
             };

         }
         String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);
    resp.getWriter().println(json);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        Object result ;
        try {
            result = new Object() {
                public final boolean success = true;
                public final Object data = doPostInner(req, resp);
            };
        }catch(Exception exc){
            result = new Object(){
                public final boolean success = false;
                public final String reason = exc.getMessage();
            };

        }
        String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);
        resp.getWriter().println(json);
    }
    protected Object doGetInner(HttpServletRequest req,HttpServletResponse resp)throws SQLException,ServletException,IOException,APIException{
          throw new APIException("405");
    }
    protected Object doPostInner(HttpServletRequest req,HttpServletResponse resp)throws SQLException,ServletException,IOException,APIException{
         throw new APIException("405");
    }
}
